﻿using Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace AlarmClock.BLL
{
    /// <summary>
    /// 公共免费的天气API
    /// </summary>
    public class FreeWeatherWebApi
    {
        /// <summary>
        /// 需要的时候可以生成txt存在本地
        /// </summary>
        /// <returns></returns>
        [ObsoleteAttribute("废弃",true)]
        public static ChinaWeatherInfo GetChinaWeatherIDInfo()
        {
            try
            {
                ChinaWeatherInfo chinaWeatherInfo = new ChinaWeatherInfo();

                string url = $"http://www.weather.com.cn/data/citydata/china.html";//查省及直辖市

                using (WebClient MyWebClient = new WebClient())
                {
                    Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据
                    string jsonStr = UTF8Encoding.UTF8.GetString(pageData);

                    JObject jo = (JObject)JsonConvert.DeserializeObject(jsonStr);
                    foreach (var item in jo)
                    {
                        var province = new Province() { Id = item.Key, Name = item.Value.ToString() };
                        chinaWeatherInfo.Provinces.Add(province);

                        //根据省份ID 获取直辖市的城市
                        string url2 = $"http://www.weather.com.cn/data/citydata/district/{province.Id}.html";
                        using (WebClient MyWebClient2 = new WebClient())
                        {
                            Byte[] pageData2 = MyWebClient2.DownloadData(url2); //从指定网站下载数据
                            string jsonStr2 = UTF8Encoding.UTF8.GetString(pageData2);

                            JObject jo2 = (JObject)JsonConvert.DeserializeObject(jsonStr2);
                            foreach (var cityItem in jo2)
                            {
                                District district = new District() { Id = cityItem.Key, Name = cityItem.Value.ToString() };
                                province.Cites.Add(district);

                                //根据省市 获取区域
                                string url3 = $"http://www.weather.com.cn/data/citydata/city/{province.Id}{district.Id}.html";
                                using (WebClient MyWebClient3 = new WebClient())
                                {
                                    Byte[] pageData3 = MyWebClient3.DownloadData(url3); //从指定网站下载数据
                                    string jsonStr3 = UTF8Encoding.UTF8.GetString(pageData3);

                                    JObject jo3 = (JObject)JsonConvert.DeserializeObject(jsonStr3);
                                    foreach (var areaItem in jo3)
                                    {
                                        district.Areas.Add(new Area() { Id = areaItem.Key, Name = areaItem.Value.ToString() });
                                    }
                                }

                            }
                        }
                    }

                }

                //需要的时候可以生成txt存在本地
                foreach (var province in chinaWeatherInfo.Provinces)
                {
                    foreach (var district in province.Cites)
                    {
                        foreach (var area in district.Areas)
                        {
                            string text = $"{province.Id}:{province.Name} {district.Id}:{district.Name} {area.Id}:{area.Name}\r\n";
                            File.AppendAllText("Resourse\\FreeWeatherInfo.txt", text);
                        }
                    }
                }

                return chinaWeatherInfo;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }     
        
        /// <summary>
        /// 目前测试就一个北京能用，垃圾
        /// </summary>
        /// <param name="cityName"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static string GetWeather(string cityName)
        {
            var chinaWeatherInfo = GetWeatherInfo();

            var ret = chinaWeatherInfo.Find(a => a.Item3.Item2 == cityName);

            if (ret == default(((string, string), (string, string), (string, string))))
            {
                throw new Exception($"{cityName}不支持天气查询！");
            }

            string province = ret.Item1.Item1;
            string district = ret.Item2.Item1;
            string area = ret.Item3.Item1;

            string strAreaNumber = $"{ret.Item1.Item1}{ret.Item2.Item1}{ret.Item3.Item1}";

            int pID = int.Parse(province);
            //如果是海南省或湖北荆州沙市，则直接获取
            if (pID == 10131 || province == "沙市")
            {
                strAreaNumber = district;
            }
            else if(pID < 10105)
            {
                strAreaNumber = $"{ret.Item1.Item1}{ret.Item3.Item1}{ret.Item2.Item1}";
            }

            string url = $"http://www.weather.com.cn/data/sk/{strAreaNumber}.html";
            string pageHtml = string.Empty;
            try
            {
                if (string.IsNullOrEmpty(url))
                {
                    throw new Exception("url不能为空！");
                }

                using (WebClient MyWebClient = new WebClient())
                {
                    Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据
                    pageHtml = UTF8Encoding.UTF8.GetString(pageData);

                }
                return pageHtml;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        private static List<((string,string), (string, string), (string, string))> GetWeatherInfo()
        {
            var result = new List<((string, string), (string, string), (string, string))>();

            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resourse\FreeWeatherInfo.txt");
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    string line = "";
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] data = line.Split();
                        var province = data[0].Split(':');
                        var city = data[1].Split(':');
                        var area = data[2].Split(':');
                        result.Add((((province[0], province[1])), ((city[0], city[1])), ((area[0], area[1]))));
                    }
                }
            }
            return result;
        }

    }

}
